﻿using System.Collections.Specialized;
using System.Linq;
using System;
using System.Management;
using Microsoft.Win32;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.LookAndFeel;
using DevExpress.Skins;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraEditors;
using System.IO;
using Microsoft.ConfigurationManagement.ManagementProvider;
using Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine;

namespace SCCMHealthCheck
{
  public partial class FMain : DevExpress.XtraBars.Ribbon.RibbonForm
  {
    private SmsNamedValuesDictionary gNamedValues = new SmsNamedValuesDictionary();
    private WqlConnectionManager gConnection;
    private WMIUtil _wmiutil = new WMIUtil();
    private DataConverter _dataconverter = new DataConverter();

    private const string _SCCMHealthCheckRegistryKey = @"Software\dotNetwork\SCCMHealthCheck";

    private int _Close = 1;
    private string _server = string.Empty;
    private string _username = string.Empty;
    private string _password = string.Empty;
    private string _sitecode = string.Empty;
    private string _sqlserver = string.Empty;
    string gXMLPath = String.Empty;

    private string FormatFolder(string _Folder)
    {
      if (_Folder.Substring(_Folder.Length - 1) == "\\")
        return _Folder;
      else
        return _Folder + "\\";
    }

    public FMain()
    {
      InitializeComponent();
    }

    private void barButtonItem1_ItemClick(object sender, ItemClickEventArgs e)
    {
      _Close = 0;
      Close();
    }

    private void ShowErrorMessage(string Message, Exception ex)
    {
      MessageBox.Show(Message + " Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }

    private void ShowErrorMessage(string Message)
    {
      MessageBox.Show(Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }

    private void FMain_Load(object sender, EventArgs e)
    {
      RegistryKey _registry = Registry.CurrentUser;
      RegistryKey _regkey = _registry.OpenSubKey(_SCCMHealthCheckRegistryKey, false);
      if (_regkey != null)
      {
        edtServer.EditValue = _regkey.GetValue("server", string.Empty);
        edtLogin.EditValue = _regkey.GetValue("login", string.Empty);
        object o = _regkey.GetValue("loggeduser", 0);

        if ((int)o == 0)
          chkLoggeduser.Checked = false;
        else
          chkLoggeduser.Checked = true;

        edtXMLPath.EditValue = _regkey.GetValue("XMLPath", String.Empty);
        folderBrowserDialog1.SelectedPath = edtXMLPath.EditValue.ToString();
        gXMLPath = edtXMLPath.EditValue.ToString();

        edtWordTemplate.EditValue = _regkey.GetValue("Wordtemplate", String.Empty);

        int _max = (int)_regkey.GetValue("IsMax", 0);
        if (_max != 0)
          this.WindowState = FormWindowState.Maximized;
        else
        {
          int _width = (int)_regkey.GetValue("width", 0);
          int _height = (int)_regkey.GetValue("height", 0);
          int _top = (int)_regkey.GetValue("top", 0);
          int _left = (int)_regkey.GetValue("left", 0);
          if (_width != 0)
            this.Width = _width;

          if (_height != 0)
            this.Height = _height;

          if (_top != 0)
            this.Top = _top;

          if (_left != 0)
            this.Left = _left;
        }
      }
    }

    private void TabControlUpdate(bool show)
    {
      if (show)
        tabMain.EndUpdate();
      else
      {
        tabMain.BeginUpdate();
        while (tabMain.TabPages.Count > 1)
        {
          tabMain.SelectedTabPageIndex = tabMain.TabPages.Count - 1;
          tabMain.TabPages.Remove(tabMain.SelectedTabPage);
        }
        tabMain.TabPages[0].Select();
      }
    }

    private string RemoveDuplicateSpace(string _string)
    {
      string _str = _string.Replace("  ", " ");
      _str = _str.Replace("&lt;", "<");
      _str = _str.Replace(System.Environment.NewLine, " ");

      return _str.Replace("  ", " ").Trim();
    }

    private void btnHealthCheck_ItemClick(object sender, ItemClickEventArgs e)
    {
      _server = Convert.ToString(edtServer.EditValue);
      _username = Convert.ToString(edtLogin.EditValue);
      _password = Convert.ToString(edtPassword.EditValue);
      if ((_server == "") || (_server == "."))
      {
        _server = "localhost";
        edtServer.EditValue = _server;
      }

      if (_server != "localhost")
      {
        if (String.IsNullOrEmpty(_username) || String.IsNullOrEmpty(_password))
        {
          ShowErrorMessage("Connecting to a remote server is necessary type username and password");
          return;
        }
      }

      try
      {
        gConnection = new WqlConnectionManager(gNamedValues);

        if (_server == "localhost")
          gConnection.Connect(_server);
        else
          gConnection.Connect(_server, _username, _password);


        _wmiutil.CreateScope("sms", _server, _username, _password);
        ManagementObjectSearcher _searcher = _wmiutil.WMIQuery("sms", "select SiteCode from SMS_ProviderLocation");

        foreach (ManagementObject queryObj in _searcher.Get())
        {
          _sitecode = queryObj["SiteCode"].ToString();
        }

        IResultObject _result = gConnection.QueryProcessor.ExecuteQuery("select ServerName from SMS_SystemResourceList where RoleName = 'SMS SQL Server'");
        foreach (IResultObject data in _result)
        {
          _sqlserver = data["ServerName"].StringValue;
        }

        HealthCheck();
      }
      catch (SmsException ex)
      {
        ShowErrorMessage("Failed to Connect. Error: " + ex.Message);
      }
      catch (UnauthorizedAccessException ex)
      {
        ShowErrorMessage("Failed to authenticate. Error:" + ex.Message);
      }
      catch (Exception ex)
      {
        MessageBox.Show(ex.Message);
      }
    }

    private void HealthCheck()
    {
      TabControlUpdate(false);
      try
      {
        if (!File.Exists(FormatFolder(gXMLPath) + "HealthCheck.xml"))
        {
          ShowErrorMessage("File '" + FormatFolder(gXMLPath) + "HealthCheck.xml' does not exist");
          return;
        }

        DataSet xmlDataSet = new DataSet();
        xmlDataSet.ReadXml(FormatFolder(gXMLPath) + "HealthCheck.xml");

        foreach (DataRow rw in xmlDataSet.Tables["item"].Rows)
        {
          if (rw["active"].ToString() == "1")
            CreateXMLTab(rw["xml"].ToString());
        }

      }
      catch (Exception ex)
      {
        ShowErrorMessage("Unable to Perform Health Check.", ex);
      }
      finally
      {
        TabControlUpdate(true);
      }
    }

    private DevExpress.XtraTab.XtraTabPage CreateDevExpressTab(DevExpress.XtraTab.XtraTabControl _tabControl, string _name, string _desc, DockStyle _Fill)
    {
      DevExpress.XtraTab.XtraTabPage _return = _tabControl.TabPages.Add();
      _return.Name = _name;
      _return.Text = _desc;
      _return.Dock = _Fill;

      return _return;
    }

    private void CreateDevExpressGrid(string _type, DataTable _table, DevExpress.XtraTab.XtraTabPage _control, DataRow[] _rowFields)
    {
      DevExpress.XtraGrid.GridControl oControl = new DevExpress.XtraGrid.GridControl();
      DevExpress.XtraGrid.Views.Grid.GridView oView = new DevExpress.XtraGrid.Views.Grid.GridView(oControl);
      oView.OptionsBehavior.Editable = false;
      oView.OptionsCustomization.AllowGroup = false;
      oView.OptionsView.ShowGroupPanel = false;
      oControl.MainView = oView;
      oControl.Dock = DockStyle.Fill;
      _control.Controls.Add(oControl);
      oControl.DataSource = _table;

      switch (_type.ToLower())
      {
        case "list":
          oView.OptionsView.ShowColumnHeaders = false;

          oControl.RefreshDataSource();
          oControl.ForceInitialize();
          //oView.Columns[0].Width = Math.Abs(_width / 2);
          oView.PopulateColumns(oControl.DataSource);
          oView.RefreshData();
          break;
        case "grid":

          oControl.RefreshDataSource();
          oControl.ForceInitialize();
          oView.PopulateColumns(oControl.DataSource);
          oView.RefreshData();
          oView.BestFitColumns();

          if (_rowFields != null)
          {
            oView.Columns.Clear();
            foreach (DataRow rw in _rowFields)
            {
              DevExpress.XtraGrid.Columns.GridColumn oColumn = oView.Columns.Add();
              oColumn.FieldName = rw["name"].ToString();
              oColumn.Caption = rw["description"].ToString();
              oColumn.OptionsColumn.AllowEdit = false;
              oColumn.Visible = true;
              if (rw["bestfit"].ToString() == "true")
                oColumn.Tag = 1;
              else
                oColumn.Tag = 0;
            }
          }
          oView.BestFitColumns();
          for (int liCount = 0; liCount < oView.Columns.Count; liCount++)
          {
            try
            {
              if (oView.Columns[liCount].Tag.ToString() == "1")
              {
                oView.Columns[liCount].Width = oView.Columns[liCount].Width - 1;
                oView.Columns[liCount].BestFit();
              }
            }
            catch
            {
            }
          }

          break;
      }
    }

    private void AddWMIRootToListDataSet(DataRow _sql, DataRow[] _rowFields, DataTable myTable)
    {
      _wmiutil.CreateScope("root", _server, _username, _password);
      ManagementObjectSearcher _searcher = _wmiutil.WMIQuery("root", _sql["query"].ToString());
      ManagementObject schema = _searcher.Get().OfType<ManagementObject>().FirstOrDefault();
      foreach (ManagementObject service in _searcher.Get())
      {
        foreach (var item in service.Properties)
        {
          foreach (DataRow rw in _rowFields)
          {
            if (item.Name.ToLower() == rw["name"].ToString().ToLower())
            {
              if (rw["queryID"].ToString() != _sql["id"].ToString()) continue;
              DataRow dr = myTable.NewRow();
              dr["value"] = PopulateValue(item.Name, item.Value.ToString(), rw["value"].ToString(), rw["format"].ToString());
              dr["name"] = rw["description"].ToString().Trim();
              myTable.Rows.Add(dr);
              break;
            }
          }
        }
      }
    }

    private void AddSiteToListDataSet(DataRow _sql, DataRow[] _rowFields, DataTable myTable)
    {
      IResultObject _result = gConnection.QueryProcessor.ExecuteQuery(_sql["query"].ToString().Replace("@@SITECODE@@", _sitecode));
      foreach (IResultObject data in _result)
      {
        foreach (string Field in data.PropertyNames)
        {
          switch (Field.ToLower())
          {
            case "props":
              foreach (DataRow rw in _rowFields)
              {
                if (rw["queryID"].ToString() != _sql["id"].ToString()) continue;
                if (data.EmbeddedProperties.ContainsKey(rw["name"].ToString()))
                {
                  DataRow dr = myTable.NewRow();
                  string _FieldName = rw["name"].ToString().Trim();

                  dr["name"] = rw["Description"].ToString().Trim();
                  dr["value"] = PopulateValue(_FieldName, data.EmbeddedProperties[_FieldName][rw["props"].ToString()].StringValue, rw["value"].ToString(), rw["format"].ToString());
                  myTable.Rows.Add(dr);
                }
              }
              break;
            case "multivalue":
              break;
            case "regmultistringlists":
              foreach (DataRow rw in _rowFields)
              {
                if (data.RegMultiStringLists.ContainsKey(rw["name"].ToString()))
                {
                  DataRow dr = myTable.NewRow();
                  string _FieldName = rw["name"].ToString().Trim();

                  dr["name"] = rw["Description"].ToString().Trim();
                  foreach (string _value2 in data.RegMultiStringLists[rw["name"].ToString()][rw["props"].ToString().Substring(4)].StringArrayValue)
                  {
                    if (!String.IsNullOrEmpty(dr["value"].ToString()))
                      dr["value"] += ", ";

                    dr["value"] = PopulateValue(_FieldName, _value2, rw["value"].ToString(), rw["format"].ToString());
                  }
                  break;
                }
              }
              break;
            case "proplists":
              foreach (DataRow rw in _rowFields)
              {
                if (rw["queryID"].ToString() != _sql["id"].ToString()) continue;
                if (rw["props"].ToString().IndexOf('#') == -1) continue;
                if (data.EmbeddedPropertyLists.ContainsKey(rw["name"].ToString()))
                {
                  DataRow dr = myTable.NewRow();
                  string _FieldName = rw["name"].ToString().Trim();

                  dr["name"] = rw["Description"].ToString().Trim();
                  foreach (KeyValuePair<string, IResultObject> kvp in data.EmbeddedPropertyLists)
                  {
                    if (!String.IsNullOrEmpty(dr["value"].ToString()))
                      dr["value"] += ", ";

                    dr["value"] = PopulateValue(_FieldName, kvp.Value.PropertyList[rw["props"].ToString().Substring(5)].ToString(), rw["value"].ToString(), rw["format"].ToString());
                  }
                  myTable.Rows.Add(dr);
                }
              }
              break;
            default:
              foreach (DataRow rw in _rowFields)
              {
                if (rw["queryID"].ToString() != _sql["id"].ToString()) continue;
                if (Field.ToLower() == rw["name"].ToString().ToLower())
                {
                  DataRow dr = myTable.NewRow();
                  dr["value"] = PopulateValue(Field, data[Field].StringValue, rw["value"].ToString(), rw["format"].ToString());
                  dr["name"] = rw["description"].ToString().Trim();
                  myTable.Rows.Add(dr);
                  break;
                }
              }
              break;
          }
        }
      }
    }

    private void CreateList(DevExpress.XtraTab.XtraTabControl _tabControl, string _HealthCheckName, string _name, string _desc, DataRow row)
    {
      DevExpress.XtraTab.XtraTabPage _tabList = CreateDevExpressTab(_tabControl, _name, _desc, DockStyle.Fill);

      DataSet myDataSet = new DataSet();
      myDataSet.Tables.Clear();
      myDataSet.Tables.Add(_HealthCheckName);
      myDataSet.Tables[_HealthCheckName].Columns.Add("name", typeof(string));
      myDataSet.Tables[_HealthCheckName].Columns.Add("value", typeof(string));

      foreach (DataRow row12 in row.GetChildRows("tab_fields"))
      {
        DataRow[] _rowFields = row12.GetChildRows("fields_field");

        foreach (DataRow row2 in row.GetChildRows("tab_sqls"))
        {
          foreach (DataRow row3 in row2.GetChildRows("sqls_sql"))
          {
            switch (row3["type"].ToString().ToLower())
            {
              case "root":
                AddWMIRootToListDataSet(row3, _rowFields, myDataSet.Tables[_HealthCheckName]);
                break;
              case "site":
                AddSiteToListDataSet(row3, _rowFields, myDataSet.Tables[_HealthCheckName]);
                break;
              case "sql":
                break;
            }
          }
        }
      }
      CreateDevExpressGrid("list", myDataSet.Tables[_HealthCheckName], _tabList, null);
    }

    private void CreateXMLTab(string _xml)
    {
      if (!File.Exists(FormatFolder(gXMLPath) + _xml))
        return;

      DataSet xmlDataSet = new DataSet();
      xmlDataSet.ReadXml(FormatFolder(gXMLPath) + _xml);

      string _name = xmlDataSet.Tables["healthcheck"].Rows[0]["name"].ToString();
      string _desc = xmlDataSet.Tables["healthcheck"].Rows[0]["description"].ToString();

      DevExpress.XtraTab.XtraTabPage _tab = CreateDevExpressTab(tabMain, _name, _desc, DockStyle.Fill);
      
      DevExpress.XtraTab.XtraTabControl _tabControl = new DevExpress.XtraTab.XtraTabControl();
      _tabControl.Dock = DockStyle.Fill;
      _tab.Controls.Add(_tabControl);
      _tab.ShowCloseButton = DevExpress.Utils.DefaultBoolean.True;

      foreach (DataRow row in xmlDataSet.Tables["tab"].Rows)
      {
        switch (row["active"].ToString().ToLower())
        {
          case "0":
            continue;
          case "isnativemode":
          case "ismixedmode":
            bool _continue = false;
            IResultObject _result = gConnection.QueryProcessor.ExecuteQuery("select props from sms_sci_component where sitecode='" + _sitecode + "' and componentname='SMS_SITE_COMPONENT_MANAGER'");
            foreach (IResultObject data in _result)
            {
              foreach (string Field in data.PropertyNames)
              {
                if (Field.ToLower() == "props")
                {
                  if (data.EmbeddedProperties.ContainsKey("IISSSLState"))
                  {
                    if (row["active"].ToString().ToLower() == "ismixedmode")
                      _continue = data.EmbeddedProperties["IISSSLState"]["value"].StringValue != "0";

                    if (row["active"].ToString().ToLower() == "isnativemode")
                      _continue = data.EmbeddedProperties["IISSSLState"]["value"].StringValue == "0";
                    break;
                  }
                }
              }
            }
            if (_continue)
              continue;
            break;
          default:
            break;
        }

        switch (row["type"].ToString().ToLower())
        {
          case "list":
            CreateList(_tabControl, _name, _tab.Name + row["name"].ToString(), row["Description"].ToString(), row);
            break;
          case "grid":
            CreateGrid(_tabControl, _name, _tab.Name + row["name"].ToString(), row["Description"].ToString(), row, xmlDataSet);
            break;
        }
      }
    }

    private void CreateGrid(DevExpress.XtraTab.XtraTabControl _tabControl, string _HealthCheckName, string _name, string _desc, DataRow row, DataSet xmlDataSet)
    {
      DevExpress.XtraTab.XtraTabPage _tabGrid = CreateDevExpressTab(_tabControl, _name, _desc, DockStyle.Fill);

      DataSet myDataSet = new DataSet();
      myDataSet.Tables.Clear();
      myDataSet.Tables.Add(_name);

      foreach (DataRow row12 in row.GetChildRows("tab_fields"))
      {
        DataRow[] _rowFields = row12.GetChildRows("fields_field");

        foreach (DataRow row2 in row.GetChildRows("tab_sqls"))
        {
          foreach (DataRow row3 in row2.GetChildRows("sqls_sql"))
          {
            switch (row3["type"].ToString().ToLower())
            {
              case "root":
                break;
              case "sql":
                break;
              case "site":
                if (xmlDataSet.Tables.Contains("field"))
                {
                  foreach (DataRow rw in _rowFields)
                  {
                    DataColumn dc = myDataSet.Tables[_name].Columns.Add(rw["name"].ToString().Trim(), typeof(string));
                    dc.Caption = rw["Description"].ToString();
                  }

                  IResultObject _result = gConnection.QueryProcessor.ExecuteQuery(row3["query"].ToString().Replace("@@SITECODE@@", _sitecode));
                  foreach (IResultObject data in _result)
                  {
                    DataRow dr = myDataSet.Tables[_name].NewRow();
                    foreach (string Field in data.PropertyNames)
                    {
                      switch (Field.ToLower())
                      {
                        case "props":
                          foreach (DataRow rw in _rowFields)
                          {
                            if (data.EmbeddedProperties.ContainsKey(rw["name"].ToString()))
                            {
                              string _FieldName = rw["name"].ToString().Trim();
                              dr[_FieldName] = PopulateValue(_FieldName, data.EmbeddedProperties[_FieldName][rw["props"].ToString()].StringValue, rw["value"].ToString(), rw["format"].ToString());
                            }
                          }
                          break;
                        case "multivalue":
                          break;
                        case "regmultistringlists":
                          foreach (DataRow rw in _rowFields)
                          {
                            if (data.RegMultiStringLists.ContainsKey(rw["name"].ToString()))
                            {
                              string _FieldName = rw["name"].ToString().Trim();

                              foreach (string _value2 in data.RegMultiStringLists[rw["name"].ToString()][rw["props"].ToString().Substring(4)].StringArrayValue)
                              {
                                if (!String.IsNullOrEmpty(dr[_FieldName].ToString()))
                                  dr[_FieldName] += ", ";

                                dr[_FieldName] += PopulateValue(_FieldName, _value2, rw["value"].ToString(), rw["format"].ToString());
                              }
                            }
                          }
                          break;
                        case "proplists":
                          foreach (DataRow rw in _rowFields)
                          {
                            if (data.EmbeddedPropertyLists.ContainsKey(rw["name"].ToString()))
                            {
                              string _FieldName = rw["name"].ToString().Trim();

                              foreach (KeyValuePair<string, IResultObject> kvp in data.EmbeddedPropertyLists)
                              {
                                if (!String.IsNullOrEmpty(dr[_FieldName].ToString()))
                                  dr[_FieldName] += ", ";

                                dr[_FieldName] += PopulateValue(_FieldName, kvp.Value.PropertyList[rw["props"].ToString().Substring(5)].ToString(), rw["value"].ToString(), rw["format"].ToString());
                              }
                              break;
                            }
                          }
                          break;
                        default:
                          foreach (DataRow rw in _rowFields)
                          {
                            if (Field.ToLower() == rw["name"].ToString().ToLower())
                              dr[Field] = PopulateValue(Field, data[Field].StringValue, rw["value"].ToString(), rw["format"].ToString());
                          }
                          break;
                      }
                    }
                    myDataSet.Tables[_name].Rows.Add(dr);
                  }
                }
                CreateDevExpressGrid("grid", myDataSet.Tables[_name], _tabGrid, _rowFields);
                break;
            }
          }
        }
      }
    }

    private string ConvertMemory(string memory)
    {
      if (memory.Trim() == "")
        return "";
      else
      {
        int liCount = 0;
        string _return = String.Empty;
        long _mem = Convert.ToInt64(memory);
        long _memtemp = _mem / 1024;
        while (Math.Abs(_memtemp) > 0)
        {
          _mem = _mem / 1024;
          _memtemp = _memtemp / 1024;
          liCount++;
        }
        switch (liCount)
        {
          case 0:
            _return = "bytes";
            break;
          case 1:
            _return = "KB";
            break;
          case 2:
            _return = "MB";
            break;
          case 3:
            _return = "GB";
            break;
          case 4:
            _return = "TB";
            break;
        }
        return Convert.ToString(_mem) + " " + _return;
      }
    }

    private string PopulateValue(string _FieldName, string _WMIData, string _QueryData, string _format)
    {
      string _return = "";

      if (string.IsNullOrEmpty(_QueryData))
      {
        _return = _WMIData;
        switch (_format.ToString())
        {
          case "1":
            _return = Convert.ToString(Math.Abs(Convert.ToInt32(_return) / 60));
            break;
          case "2":
            _return = Convert.ToString(Math.Abs(Convert.ToInt32(_return) / 3600));
            break;
          case "3":
            _return = ManagementDateTimeConverter.ToDateTime(_return).ToLongDateString();
            break;
          case "4":
            _return = ConvertMemory(_return);
            break;
          case "5":
            if (_return.IndexOf("SubjectStr") >= 0)
              _return = "Certificate criteria: subject contains string " + _return.Substring(_return.IndexOf(":") + 1);
            else if (_return.IndexOf("SubjectAttr") >= 0)
              _return = "Certificate criteria: subject or alt includes attributes " + _return.Substring(_return.IndexOf(":") + 1);
            else
              _return = "Certificate criteria: Check only certificate purpose";
            break;
          case "6"://Normal schedule, Simple schedule
            _return = "I need fix it!! (6)";
            break;
          case "7"://Mobile device schedule schedule, every x (days, weeks, etc)
            int _length = _return.Length;
            int _minutes = Convert.ToInt32(_return.Substring(_length-5,2));
            int _hours = Convert.ToInt32(_return.Substring(_length-8,2));
            int _days = Convert.ToInt32(_return.Substring(_length-11,2));
            int _months = Convert.ToInt32(_return.Substring(_length-14,2));
            if (_minutes != 0)
              _return = _minutes.ToString() + " minutes";
            else if (_hours != 0)
              _return = _hours.ToString() + " hours";
            else if (_days != 0)
            {
              int remainder;
              Math.DivRem(_days, 7, out remainder);
              if (remainder == 0)
                _return = Convert.ToString(_days / 7) + " weeks";
              else
                _return = _days.ToString() + " days";
            }
            else if (_months != 0)
              _return = _months.ToString() + " months";

            break;
        }
      }
      else
      {
        string[] _values = _QueryData.Split(';');

        foreach (string _value in _values)
        {
          if (_WMIData.ToLower().Equals(_value.Substring(0, _value.IndexOf("=")).ToLower()))
          {
            _return = _value.Substring(_value.IndexOf("=") + 1);
            break;
          }
        }
      }

      switch (_FieldName.ToLower())
      {
        case "brandingtitle":
        case "sumbrandingsubtitle":
        case "swdbrandingsubtitle":
        case "osdbrandingsubtitle":
          _return = DecodeText(_return);
          break;
      }

      return _return;
    }

    private void AddWMIRootToDataSet(DataSet myDataSet, DataSet xmlDataSet, string _name, string _sql, string _queryID)
    {
      _wmiutil.CreateScope("root", _server, _username, _password);

      ManagementObjectSearcher _searcher = _wmiutil.WMIQuery("root", _sql);
      ManagementObject schema = _searcher.Get().OfType<ManagementObject>().FirstOrDefault();

      foreach (ManagementObject service in _searcher.Get())
      {
        foreach (var item in service.Properties)
        {
          if (xmlDataSet.Tables.Contains("field"))
          {
            foreach (DataRow rw in xmlDataSet.Tables["field"].Rows)
            {
              if (item.Name.ToLower() == rw["name"].ToString().ToLower())
              {
                if (rw["queryID"].ToString() != _queryID) continue;
                DataRow dr = myDataSet.Tables[_name].NewRow();
                //dr["name"] = item.Name.Trim();
                //dr["value"] = _dataconverter.ConvertFrom(_name, item.Name, Convert.ToString(item.Value));
                dr["value"] = PopulateValue(item.Name, item.Value.ToString(), rw["value"].ToString(), rw["format"].ToString());
                dr["name"] = rw["description"].ToString().Trim();
                myDataSet.Tables[_name].Rows.Add(dr);
                break;
              }
            }
          }
        }
      }
    }

    public static string DecodeText(string encodedText)
    {
      string returnString = string.Empty; 
      encodedText = encodedText.Substring(6);
 
      for (int i = 0; i <= encodedText.Length; i += 4)
      {
        if (i+4 <= encodedText.Length)
        {
          if (encodedText.Substring(i + 2, 2) != "")
          {
            returnString += Convert.ToChar(Convert.ToInt32(encodedText.Substring(i + 2, 2), 16));
          }
        }
      }

      return returnString;
    }

    private void AddSiteToDataSet(string Type, DataSet myDataSet, DataSet xmlDataSet, string _name, string _sql, string _queryID)
    {
      IResultObject _result = gConnection.QueryProcessor.ExecuteQuery(_sql.Replace("@@SITECODE@@", _sitecode));
      foreach (IResultObject data in _result)
      {
        foreach (string Field in data.PropertyNames)
        {
          if (Field.ToLower() == "proplists") continue;
          if (Field.ToLower() == "props")
          {
            if (xmlDataSet.Tables.Contains("field"))
            {
              foreach (DataRow rw in xmlDataSet.Tables["field"].Rows)
              {
                if (rw["queryID"].ToString() != _queryID) continue;
                if (data.EmbeddedProperties.ContainsKey(rw["name"].ToString()))
                {
                  DataRow dr = myDataSet.Tables[_name].NewRow();
                  string _FieldName = rw["name"].ToString().Trim();

/*
                  string _value = data.EmbeddedProperties[_FieldName][rw["props"].ToString()].StringValue;

                  switch (_FieldName.ToLower())
                  {
                    case "brandingtitle":
                    case "sumbrandingsubtitle":
                    case "swdbrandingsubtitle":
                    case "osdbrandingsubtitle":
                      _value = DecodeText(_value);
                      break;
                  }
*/
                  dr["name"] = rw["Description"].ToString().Trim();
                  dr["value"] = PopulateValue(_FieldName, data.EmbeddedProperties[_FieldName][rw["props"].ToString()].StringValue, rw["value"].ToString(), rw["format"].ToString());

                  //dr["value"] = _dataconverter.ConvertFrom(_name, _FieldName, _value);
                  myDataSet.Tables[_name].Rows.Add(dr);
                }
              }
            }
          }
          else if (xmlDataSet.Tables.Contains("field"))
          {
            foreach (DataRow rw in xmlDataSet.Tables["field"].Rows)
            {
              if (rw["queryID"].ToString() != _queryID) continue;
              if (Field.ToLower() == rw["name"].ToString().ToLower())
              {
                DataRow dr = myDataSet.Tables[_name].NewRow();
                //dr["value"] = _dataconverter.ConvertFrom(_name, Field, data[Field].StringValue);
                dr["value"] = PopulateValue(Field, data[Field].StringValue, rw["value"].ToString(), rw["format"].ToString());
                dr["name"] = rw["description"].ToString().Trim();
                myDataSet.Tables[_name].Rows.Add(dr);
                break;
              }
            }
          }
        }
      }
    }

    private void MontaPaginaSimpleGrid(DataSet xmlDataSet, string _desc, string _name, string _returntype)
    {
      DevExpress.XtraTab.XtraTabPage _tab = tabMain.TabPages.Add();
      _tab.Name = _name;
      _tab.Text = _desc;

      DataSet myDataSet = new DataSet();
      myDataSet.Tables.Clear();
      myDataSet.Tables.Add(_name);

      for (int liCount = 0; liCount < xmlDataSet.Tables["Query"].Rows.Count; liCount++)
      {
        string _queryName = xmlDataSet.Tables["Query"].Rows[liCount]["name"].ToString().ToLower();
        string _queryDesc = xmlDataSet.Tables["Query"].Rows[liCount]["description"].ToString();
        string _sql = xmlDataSet.Tables["Query"].Rows[liCount]["sql"].ToString();
        string _type = xmlDataSet.Tables["Query"].Rows[liCount]["type"].ToString().ToLower();
        string _querynamespace = xmlDataSet.Tables["Query"].Rows[liCount]["namespace"].ToString().ToLower();
        string _queryID = xmlDataSet.Tables["Query"].Rows[liCount]["queryID"].ToString().ToLower();

        try
        {
          switch (_querynamespace.ToLower())
          {
            case "root":
              break;
            case "sql":
              break;
            case "site":
              if (xmlDataSet.Tables.Contains("field"))
              {
                foreach (DataRow rw in xmlDataSet.Tables["field"].Rows)
                  myDataSet.Tables[_name].Columns.Add(rw["name"].ToString().Trim(), typeof(string));

                IResultObject _result = gConnection.QueryProcessor.ExecuteQuery(_sql.Replace("@@SITECODE@@", _sitecode));
                foreach (IResultObject data in _result)
                {
                  DataRow dr = myDataSet.Tables[_name].NewRow();
                  foreach (string Field in data.PropertyNames)
                  {
                    if (Field.ToLower() == "proplists") continue;
                    if (Field.ToLower() == "props")
                    {
                    }
                    else
                    {
                      foreach (DataRow rw in xmlDataSet.Tables["field"].Rows)
                      {
                        if (Field.ToLower() == rw["name"].ToString().ToLower())
                        {
                          //dr[Field] = _dataconverter.ConvertFrom(_name, Field, data[Field].StringValue);
                          dr[Field] = PopulateValue(Field, data[Field].StringValue, rw["value"].ToString(), rw["format"].ToString());
                          break;
                        }
                      }
                    }
                  }
                  myDataSet.Tables[_name].Rows.Add(dr);
                }
              }
              break;
          }

        }
        catch (Exception ex)
        {
          ShowErrorMessage("Unable to execute WMI command", ex);
          throw;
        }
      }

      DevExpress.XtraGrid.GridControl oControl = new DevExpress.XtraGrid.GridControl();
      DevExpress.XtraGrid.Views.Grid.GridView oView = new DevExpress.XtraGrid.Views.Grid.GridView(oControl);

      oView.OptionsBehavior.Editable = false;
      oView.OptionsCustomization.AllowGroup = false;
      oView.OptionsView.ShowGroupPanel = false;
      //oView.OptionsView.ShowColumnHeaders = false;
      oControl.MainView = oView;

      oControl.DataSource = myDataSet.Tables[_name];

      _tab.Controls.Add(oControl);
      oControl.Dock = DockStyle.Fill;

      oControl.RefreshDataSource();
      oControl.ForceInitialize();
      oView.PopulateColumns(oControl.DataSource);
      oView.RefreshData();
      oView.BestFitColumns();

      if (xmlDataSet.Tables.Contains("field"))
      {
        oView.Columns.Clear();
        foreach (DataRow rw in xmlDataSet.Tables["field"].Rows)
        {
          DevExpress.XtraGrid.Columns.GridColumn oColumn = oView.Columns.Add();
          oColumn.FieldName = rw["name"].ToString();
          oColumn.Caption = rw["description"].ToString();
          oColumn.OptionsColumn.AllowEdit = false;
          oColumn.Visible = true;
          if (rw["bestfit"].ToString() == "true")
            oColumn.Tag = 1;
          else
            oColumn.Tag = 0;
        }
      }
      oView.BestFitColumns(); 
      for (int liCount = 0; liCount < oView.Columns.Count; liCount++)
      {
        try
        {
          if (oView.Columns[liCount].Tag.ToString() == "1")
          {
            oView.Columns[liCount].Width = oView.Columns[liCount].Width - 1;
            oView.Columns[liCount].BestFit();
          }
        }
        catch
        {
        }
      }
    }

    private void btnNew_ItemClick(object sender, ItemClickEventArgs e)
    {
//      ShowErrorMessage(_dataconverter.ScheduleConverter("0001200000100008"));
//      return;
      TabControlUpdate(false);
      TabControlUpdate(true);
    }

    private void edtXMLPath_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
    {
      if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
      {
        edtXMLPath.EditValue = folderBrowserDialog1.SelectedPath;
        gXMLPath = folderBrowserDialog1.SelectedPath;
      }
    }

    private void edtXMLPath_KeyPress(object sender, KeyPressEventArgs e)
    {
      e.Handled = true;
    }

    private void chkLoggeduser_CheckStateChanged(object sender, EventArgs e)
    {
      if (chkLoggeduser.Checked)
      {
        edtLogin.EditValue = null;
        edtPassword.EditValue = null;
        edtLogin.Properties.ReadOnly = true;
        edtPassword.Properties.ReadOnly = true;
      }
      else
      {
        edtLogin.Properties.ReadOnly = false;
        edtPassword.Properties.ReadOnly = false;
      }
    }

    private void FMain_FormClosing(object sender, FormClosingEventArgs e)
    {
      RegistryKey _registry = Registry.CurrentUser;
      RegistryKey _regkey = _registry.OpenSubKey(_SCCMHealthCheckRegistryKey, true);
      if (_regkey == null)
      {
        _registry.CreateSubKey(_SCCMHealthCheckRegistryKey);
        _regkey.OpenSubKey(_SCCMHealthCheckRegistryKey, true);
      }
        
      if (_regkey != null)
      {
        _regkey.SetValue("server", edtServer.EditValue.ToString());
        _regkey.SetValue("login", edtLogin.EditValue.ToString());
        if (chkLoggeduser.Checked)
          _regkey.GetValue("loggeduser", 1);
        else
          _regkey.GetValue("loggeduser", 0);
        if (this.WindowState == FormWindowState.Maximized)
          _regkey.SetValue("IsMax", 1);
        else
          _regkey.SetValue("IsMax", 0);

        _regkey.SetValue("width", this.Width);
        _regkey.SetValue("height", this.Height);
        _regkey.SetValue("top", this.Top);
        _regkey.SetValue("left", this.Left);
        _regkey.SetValue("XMLPath", edtXMLPath.EditValue.ToString());
        _regkey.SetValue("Wordtemplate", edtWordTemplate.EditValue.ToString());

        _regkey.Flush();
      }

      System.Environment.ExitCode = _Close;
    }

    private void edtWordTemplate_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
    {
      if (openFileDialog1.ShowDialog() == DialogResult.OK)
      {
        edtWordTemplate.EditValue = openFileDialog1.FileName;
      }
    }

    private void barButtonItem1_ItemClick_1(object sender, ItemClickEventArgs e)
    {
      FAbout _fAbout = new FAbout();
      try
      {
        _fAbout.ShowDialog();
      }
      finally
      {
        _fAbout.Dispose();
      }
    }
  }
}